import os
import subprocess

import re
import shutil




class OfficeDocument:
    """OfficeDocument is txt file."""
    def __init__(self, file_path):
        self.file_path = file_path # full path with file name
        self.ext = os.path.splitext(self.file_path)[1]
        self.file_path_txt = os.path.splitext(self.file_path)[0] + '.txt'


    def clean_up(self):
        self.docx2txt()
        contents = self.read_content()
        title = self.parse_title(contents)
        send_date = self.parse_date(contents)

        new_name = title.strip('_') + '_' + send_date.strip('')

        self.cp(new_name.replace('\"', '').replace('<', '').replace('>', ''))
        pass

    def docx2txt(self):
        cmd = 'morning-glory.exe' + ' "' + self.file_path + '"'
        subprocess.call(cmd)

    def cp(self, new_name):
        if os.path.exists('dst') == False:
            os.mkdir('dst')

        print('rename from %s to %s\n' % (self.file_path, 'dst/' + new_name + self.ext))
        shutil.copyfile(self.file_path, 'dst/' + new_name + self.ext)
        # os.rename(self.file_path, 'dst/' + new_name + self.ext)
        pass

    def read_content(self):
        f = open(self.file_path_txt)
        contents = f.readlines()
        f.close()
        return contents
        
    def parse_title(self, contents):
        send_to = re.compile(r'\S[：:]$')
        kong = re.compile(r'^\s$')
        result = []
        for line in contents:
            if re.search(kong, line) != None:
               continue
            result.append(line.strip())

            if re.search(send_to, line) != None:
                break

        # print(result[0] + '_' + ''.join(result[1:-1]))
        return result[0] + '_' + ''.join(result[1:-1])

    def parse_date(self, contents):
        fa = re.compile(r'\s玉溪市发展和改革委员会')
        chao = re.compile(r'^抄送：')
    
        result = []
        flag = False
        for line in contents:
            if re.search(fa, line) != None:
                flag = True
            if re.search(chao, line) != None:
                flag = False
                break
            if flag:
                result.append(line.strip())
    
            pass
        dd = ''.join(result)
        luo = re.compile(r'\d{4}年\d{1,2}月\d{1,2}日')
        if re.search(luo, dd) != None:
            # print(re.search(luo, dd).group())
            return re.search(luo, dd).group()


def filter_txt(file_name):
    return os.path.splitext(file_name)[1] == '.txt'


def main():

    folder = input('Please input the folder with office documents: \n$ ')
    file_list = os.listdir(folder)
    cwd = os.getcwd()

    for f in file_list:
        if filter_txt(f):
            continue
        office_document = OfficeDocument(cwd + '\\' + folder + '\\' + f)
        office_document.clean_up()

    print('done')


if __name__ == '__main__':
    main()

